package com.goldenKey.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.goldenKey.admin.pojo.query.AccountQuery;
import com.goldenKey.admin.service.IAccountService;
import com.goldenKey.common.component.AccountComponent;
import com.goldenKey.common.component.RedisComponent;
import com.goldenKey.common.constant.Constant;
import com.goldenKey.common.exception.AppException;
import com.goldenKey.common.pojo.enumeration.ExceptionEnum;
import com.goldenKey.common.pojo.result.R;
import com.goldenKey.admin.pojo.vo.AccountVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@RestController
@Slf4j
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private IAccountService accountService;
    @Resource
    private RedisComponent redisComponent;
    @Resource
    private AccountComponent accountComponent;

    /**
     * 生成图形验证码
     * @param response
     * @throws IOException
     */
    @PostMapping("/setCaptcha")
    public void setCaptcha(HttpServletResponse response) throws IOException {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 40, 4, 40);
        String captchaKey = redisComponent.saveCaptchaKey(captcha.getCode());

        response.setContentType("image/png");
        // 设置验证码 Key 到响应头
        response.setHeader(Constant.CAPTCHA_KEY, captchaKey);

        captcha.write(response.getOutputStream());

    }

    /**
     * 管理员登陆
     * @param accountQuery
     * @return
     */
    @PostMapping("/login")
    public R<AccountVo> login(@Validated @RequestBody AccountQuery accountQuery) {
        // 验证验证码是否正确
        String captcha = redisComponent.getCaptcha(accountQuery.getCaptchaKey());
        if (captcha == null) {
            throw new AppException(ExceptionEnum.CODE_EXPIRED);
        } else if(!captcha.equalsIgnoreCase(accountQuery.getCaptcha())) {
            throw new AppException(ExceptionEnum.CODE_ERROR);
        }

        AccountVo accountVo = accountService.login(accountQuery);

        // 在缓存中设置管理员token
        redisComponent.saveAdminToken(accountVo.getAdminId(), accountVo.getAdminToken());
        return R.ok(accountVo);
    }

    /**
     * 管理员退出登录
     * @param adminId
     * @return
     */
    @PostMapping("/logout")
    public R<Void> logout(Integer adminId) {

        // 删除缓存中的token
        redisComponent.deleteAdminToken(adminId);

        return R.ok();
    }

}
